/*
 * @Author: dingpanfeng
 * @Date: 2020-12-02 09:46:51
 * @LastEditors: dingpanfeng
 * @LastEditTime: 2021-01-08 17:03:35
 * @FilePath: /pmis-project/src/utils/authorized.js
 */
import Keycloak from 'keycloak-js'
const config = JSON.parse(process.env.VUE_APP_KEYCLOAK)

console.log(config)
const _kc = new Keycloak(config)
export const initKeycloak = (onAuthenticatedCallback) => {
  _kc.init({ onLoad: 'login-required', checkLoginIframe: false })
    .then((authenticated) => {
      if (authenticated) {
        onAuthenticatedCallback()
      } else {
        console.warn('not authenticated!')
        login()
      }
    })
}
export const login = _kc.login
export const logout = _kc.logout
export const getToken = () => _kc.token
export const updateToken = (successCallback) => {
  return _kc.updateToken(5)
    .then(successCallback)
    .catch(login)
}
export const getUsername = () => _kc.tokenParsed.preferred_username
export const getGivenName = () => _kc.tokenParsed.given_name
export const getJobNumber = () => _kc.tokenParsed.jobN8umber
